package ReviewAlgorithms.sort;

import java.util.Arrays;
import java.util.List;

public class FingStrInCondition {

    public static void main(String[] args) {
        String s = "abpcplea";
        String[] dc = {"a","b","c"};
        List<String> d = Arrays.asList(dc);
        System.out.println(findLongestWord(s,d));
    }

    public static String findLongestWord(String s, List<String> d) {
        if (s == null || d == null || s.length() < 1 || d.size() < 1){
            return null;
        }
        int length = 0;
        String res = "";
        for (String str : d) {
            if (legal(s,str)){
                if (length < str.length()){
                    length = str.length();
                    res = str;
                }else if (length == str.length() && str.compareTo(res) < 0){
                    res = str;
                }
            }
        }
        return res;
    }

    private static boolean legal(String s, String str) {
        if (s == null || str == null){
            return true;
        }
        if (str.length() > s.length()){
            return false;
        }
        int index = 0;
        for (int i = 0;i < s.length(); i ++){
            if (index >= str.length()){
                return true;
            }
            if (s.charAt(i) == str.charAt(index)){
                index ++;
            }
        }
        if (index >= str.length()){
            return true;
        }else {
            return false;
        }
    }
}
